package com.Yukiha.gachamod.item;

import com.Yukiha.gachamod.Data.GachaSavedData;
import com.Yukiha.gachamod.Data.ModelInfoManager;
import com.Yukiha.gachamod.Data.PlayerGachaData;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.UseAnim;
import net.minecraft.world.level.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;

public class GachaTicketItem extends Item {

    private static final Logger LOGGER = LogManager.getLogger("GachaMod");
    private static final Path MODEL_JSON_PATH = Path.of("config/gachamod/models.json");
    private static final Map<String, List<String>> MODEL_POOL_BY_RARITY = new HashMap<>();

    private String rarity;

    public GachaTicketItem(String rarity, Properties properties) {
        super(properties);
        this.rarity = rarity;
    }

    static {
        loadModelPoolByRarity();
    }

    public static void loadModelPoolByRarity() {
        if (!Files.exists(MODEL_JSON_PATH)) {
            System.err.println("[GachaMod] 模型配置文件不存在：" + MODEL_JSON_PATH);
            return;
        }

        try (Reader reader = Files.newBufferedReader(MODEL_JSON_PATH)) {
            JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();

            for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
                String rarity = entry.getKey();
                JsonArray array = entry.getValue().getAsJsonArray();

                List<String> models = new ArrayList<>();
                for (JsonElement element : array) {
                    models.add(element.getAsString());
                }

                MODEL_POOL_BY_RARITY.put(rarity, models);
            }

            LOGGER.info("[GachaMod] ✅ 模型池加载成功：已读取 " + MODEL_POOL_BY_RARITY.size() + " 个稀有度池");

        } catch (IOException | IllegalStateException e) {
            LOGGER.error("[GachaMod] ❌ 读取模型配置失败：" + e.getMessage());
        }
    }

    // 设置吃的动画
    @Override
    public UseAnim getUseAnimation(ItemStack stack) {
        return UseAnim.EAT;
    }

    // 设置持续时间（60 tick = 3 秒）
    @Override
    public int getUseDuration(ItemStack stack) {
        return 45;
    }

    // 玩家右键使用时触发（开始吃）
    @Override
    public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
        player.startUsingItem(hand); // 启动吃的动画
        return InteractionResultHolder.consume(player.getItemInHand(hand));
    }

    // 吃完后的触发（执行抽卡）
    @Override
    public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity entity) {

        if (!level.isClientSide && entity instanceof ServerPlayer player) {
            ServerLevel serverLevel = (ServerLevel) level;
            GachaSavedData savedData = GachaSavedData.get(serverLevel);
            PlayerGachaData pData = savedData.getPlayerData(player.getUUID());

            List<String> pool = MODEL_POOL_BY_RARITY.getOrDefault(this.rarity, List.of());
            List<String> unclaimed = pool.stream()
                    .filter(model -> !pData.hasDrawn(rarity, model))
                    .collect(Collectors.toList());

            if (unclaimed.isEmpty()) {
                player.displayClientMessage(Component.literal("你已经抽完了该稀有度的全部模型！"), true);
            } else {
                String drawn = unclaimed.get(new Random().nextInt(unclaimed.size()));
                pData.markDrawn(rarity, drawn);
                savedData.setDirty();

                // 调用ysm的命令授权模型
                ysmCommand(level, player, drawn);

                // 广播
                int color = switch (rarity.toLowerCase()) {
                    case "common" -> 0xAAAAAA;
                    case "rare" -> 0x00AAFF;
                    case "epic" -> 0xAA00FF;
                    case "legendary" -> 0xFFD700;
                    default -> 0xFFFFFF;
                };
                Component msg = Component.literal("玩家 " + player.getName().getString())
                        .append(Component.literal(" 抽到了 "))
                        .append(Component.literal("「" + drawn + "」").withStyle(style -> style.withColor(color)))
                        .append(Component.literal("！"));
                serverLevel.getServer().getPlayerList().broadcastSystemMessage(msg, false);

                // 示例：你在抽奖后得到了 player 和 modelId
                ModelInfoManager.ModelInfo info = ModelInfoManager.get(drawn);

                if (info != null) {
                    // 设置颜色
                    TextColor actionBarColor = switch (info.rarity().toLowerCase()) {
                        case "legendary" -> TextColor.fromRgb(0xFFD700);
                        case "epic" -> TextColor.fromRgb(0xAA00FF);
                        case "rare" -> TextColor.fromRgb(0x0099FF);
                        default -> TextColor.fromRgb(0xAAAAAA);
                    };

                    // ActionBar 内容
                    Component actionBar = Component.literal("你获得了：")
                            .append(Component.literal(info.name() + " (" + info.rarity() + ")")
                                    .withStyle(Style.EMPTY.withColor(actionBarColor))
                            );

                    // 发到客户端
                    player.connection.send(new ClientboundSetActionBarTextPacket(actionBar));
                }

            }


            // 吃掉物品
            if (!player.getAbilities().instabuild) {
                stack.shrink(1);
            }
        }

        return stack;
    }

    /**
     * 调用ysm的命令授权模型
     * @param level
     * @param player
     * @param drawn
     */
    private static void ysmCommand(Level level, ServerPlayer player, String drawn) {
        // 执行授权命令
        String command = "ysm auth " + player.getName().getString() + " add \"" + drawn + "\"";
        LOGGER.info("[GachaMod] <UNK> 命令代码为：" + command);
        try {
            level.getServer().getCommands().getDispatcher().execute(
                    command,
                    level.getServer().createCommandSourceStack()
            );
        } catch (CommandSyntaxException e) {
            throw new RuntimeException(e);
        }
    }


}
